//
//  HNNewsWebViewController.m
//  HappyNews
//
//  Created by Sai on 16/1/9.
//  Copyright © 2016年 bai wang. All rights reserved.
//

#import "HNNewsWebViewController.h"
#import "HNNewsWebViewModel.h"
#import <UIImageView+WebCache.h>
#import "HNNewsDetailController.h"
#import "MJRefresh.h"
#define kColorWithRGB(r, g, b) [UIColor colorWithRed:(r) / 255.f green:(g) / 255.f blue:(b) / 255.f alpha:1.f]
@interface HNNewsWebViewController ()<UIWebViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong)UIWebView *webView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong)HNNewsWebViewModel *model;

@property (nonatomic, strong)UIButton *backButton;

@property (nonatomic, assign)CGSize XandY;

@property (nonatomic, strong)UIScrollView *SView;

@property (nonatomic, strong)UIImageView *backImageView;

@property (nonatomic, strong)UILabel *upLoad;

@property (nonatomic, assign)BOOL isRefreshing;

@property (nonatomic, assign)BOOL isOne;

@property (nonatomic, strong)UIImageView *buttonView;

@property (nonatomic, strong)UILabel *buttonLabel;
@end

@implementation HNNewsWebViewController

- (void)dealloc
{
    
    if (_model.image != nil) {
        NSLog(@"已移除");
         [self.SView removeObserver:self forKeyPath:@"contentOffset"];
    }
        
}


- (void)viewDidLoad {
    [super viewDidLoad];
    _isRefreshing = NO;
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    _SView = [[UIScrollView alloc]init];
    _SView.delegate = self;
    
    _backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _buttonLabel = [[UILabel alloc]init];    // 加载提示
    _buttonView = [[UIImageView alloc]init];
    
    _upLoad = [[UILabel alloc]initWithFrame:CGRectMake(0, -50, kScreenWidth, 50)];
    _upLoad.textAlignment =NSTextAlignmentCenter;
    _upLoad.textColor = [UIColor lightGrayColor];
    [_SView addSubview:_upLoad];
    
   
    
    _isOne = YES;

    [self setDataUp];
    [self addWebView];
    [self.view addSubview:_titleLabel];
    
    self.tabBarController.tabBar.hidden = YES;

    
}

- (void)setDataUp
{
    _isRefreshing = YES;
   static NSInteger a = 0;
    a++;
    NSLog(@"刷新了%ld次",a);
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://news-at.zhihu.com/api/4/story/%ld",_Id]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _model = [[HNNewsWebViewModel alloc]init];
        [_model setValuesForKeysWithDictionary:dic];
        [self addWebView];
        static NSInteger i = 0;
        i++;
        NSLog(@"数据加载完成了%ld次",i);
        
        if (_isOne) {
                    _isRefreshing = NO;
            _isOne = NO;
        }

    }];
    
     
}


// 添加webView
- (void)addWebView
{
    // 每当重新加载的时候改变SView的偏移量
    [_SView setContentOffset:CGPointMake(0, 0)];

    // 结构体赋值要用第三只手如下面这样
//    CGPoint y = _SView.contentOffset;
//    y.y = 0;
//    _SView.contentOffset = y;
    
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _webView.delegate = self;
   _webView.scrollView.bounces = NO;
     _webView.scrollView.scrollEnabled = NO;
//    [_webView sizeToFit];
    
    NSString *webStr = [NSString stringWithFormat:@"<html><head><link rel=\"stylesheet\" href=%@></head><body>%@</body></html>",_model.css[0],_model.body];
//    NSString *webStr = [NSString stringWithFormat:@"<html><head><link rel=\"stylesheet\" href=></head><body>%@</body></html>",_model.body];
       [_webView loadHTMLString:webStr baseURL:nil];

}


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
//    _SView = [[UIScrollView alloc]init];
//    _SView.delegate = self;
//    // 加载提示
//    _upLoad = [[UILabel alloc]initWithFrame:CGRectMake(0, -50, kScreenWidth, 50)];
//    _upLoad.textAlignment =NSTextAlignmentCenter;
//    _upLoad.textColor = [UIColor lightGrayColor];
//    [_SView addSubview:_upLoad];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    //调整字号
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'";
    [webView stringByEvaluatingJavaScriptFromString:str];
    
    //js方法遍历图片添加点击事件 返回图片个数
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    for(var i=0;i<objs.length;i++){\
    objs[i].onclick=function(){\
    document.location=\"myweb:imageClick:\"+this.src;\
    };\
    };\
    return objs.length;\
    };";
    
    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
    [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
//
    // 通过WebView运行JS脚本代码返回的字符串获取WebView的高度
    CGFloat heihgt = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"]floatValue];
    
    // 再次设置WebView高度(点)
    webView.frame = CGRectMake(0, 64, kScreenWidth, heihgt);
    
    // 设置一个底层的ScrollView
    _backImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight/4)];
    _backImageView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight/4);
    [_backImageView sd_setImageWithURL:[NSURL URLWithString:_model.image] placeholderImage:nil];
    if (_model.image != nil) {
         [self.view addSubview:_backImageView];
    }
    
//   _webView.opaque = NO;
    
    
    [_SView addSubview:webView];
    // 添加返回按钮
//    _backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _backButton.frame = CGRectMake(0, _webView.bottom, kScreenWidth, 50);
    [self addButtonView];
    [_backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    _backButton.backgroundColor = kColorWithRGB(236, 236, 236);
    
    
    [_SView addSubview:_backButton];
    
    // 64是导航栏高度,49是tabBar高度
    _SView.frame = CGRectMake(0, 0, kScreenWidth,kScreenHeight - 49);
    _SView.contentSize = CGSizeMake(kScreenWidth,_backButton.bottom + 20);
    
    
    [self.view addSubview:_SView];
    if (_model.image != nil) {
     [self.SView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld context:nil];
         [self.view insertSubview:_backImageView aboveSubview:webView];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    UIScrollView *scrollView = object;
    CGFloat Y = scrollView.contentOffset.y;
    if (Y >= 0) {
        [UIView animateWithDuration:0.001 animations:^{
            _backImageView.frame = CGRectMake(0,  64 - Y,  kScreenWidth, kScreenHeight/4 );
            if (Y >= 20) {
                return ;
            }
        }];
    }
    if (Y <= 0 ) {
        [UIView animateWithDuration:0.001 animations:^{
            _backImageView.frame = CGRectMake(0,  64,  kScreenWidth, kScreenHeight/4 + (-Y));
        }];
        // 当他的偏移量大于SView的显示范围的时候触发加载下一界面
    
    }
    
    
    
}



// Button的点击方法
- (void)backButtonClick:(UIButton *)button
{
    HNNewsDetailController *DetailVC = [[HNNewsDetailController alloc]init];
    DetailVC.Id = _DetailId;
    [self.navigationController pushViewController:DetailVC animated:YES];
}


- (void)addButtonView
{
    _buttonView.frame = CGRectMake(10, 0, 50, 50);
    [_buttonView sd_setImageWithURL:[NSURL URLWithString:_model.theme.thumbnail] placeholderImage:nil];
    _buttonView.userInteractionEnabled = NO;
    [_backButton addSubview:_buttonView];
    
    _buttonLabel.frame = CGRectMake(_buttonView.right + 5, 10, kScreenWidth / 2, 30);
    NSString *str = [NSString stringWithFormat:@"本文来自:  %@",_model.theme.name];
    _buttonLabel.text = str;
    _buttonLabel.userInteractionEnabled = NO;
    [_backButton addSubview:_buttonLabel];
}

// ScrollView的代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y =  _SView.contentOffset.y;
    
    // 被拖拽的时候不刷新,只改变label上的文字
    if (_SView.isDragging) {
        
        // 下拉跳转到上一个界面
        if (y < 0) {
            NSString *str = [NSString stringWithFormat:@"%ld",_Id];
        // 判断当如果这个界面是第一个
        if ([str isEqualToString:_storiseArr[0]]) {
            [self.view insertSubview:_upLoad aboveSubview:_backImageView];
            _upLoad.frame = CGRectMake(0, 80, kScreenWidth, 50);
            _upLoad.text = @"上面没有了哦";
            _upLoad.textColor = [UIColor whiteColor];
        }else{
            _upLoad.frame = CGRectMake(0, -50, kScreenWidth, 50);
            _upLoad.textColor = [UIColor lightGrayColor];
            [_SView addSubview:_upLoad];
            _upLoad.text = @"载入上一篇";
        }
        
        }
        
        // 上提跳转到下一个界面
        CGFloat dY = _SView.contentSize.height - kScreenHeight;
        if (y >dY ) {
            NSString *str = [NSString stringWithFormat:@"%ld",_Id];
            // 判断如果这个界面是最后一个
            NSString *lastStr = _storiseArr.lastObject;
            if ([str isEqualToString:lastStr]) {
                _upLoad.frame = CGRectMake(0, dY + 20 + kScreenHeight, kScreenWidth, 50);
                _upLoad.text = @"最后一张啦";
                _upLoad.textColor = [UIColor lightGrayColor];
                [_SView addSubview:_upLoad];
            }else{
                _upLoad.frame = CGRectMake(0, dY + 20 + kScreenHeight, kScreenWidth, 50);
                _upLoad.text = @"载入下一界面";
                _upLoad.textColor = [UIColor lightGrayColor];
                    [_SView addSubview:_upLoad];
            }
        }
        
    }else{
        _upLoad.text = @"";
        if (_isRefreshing == YES) {
            return;
        }
        // 松手的时候开始
        if (y < -50) {
            
          NSString *str = [NSString stringWithFormat:@"%ld",_Id];
        if ([str isEqualToString:_storiseArr[0]]) {
            return;
        }else{
            for (int i = 0; i < _storiseArr.count; i++) {
                if ([str isEqualToString:_storiseArr[i]]) {
                    // 之所以要把这个保护写在这是因为当走进这里的时候"i--"使得一直持续这个操作,这是个死循环 写在这使得第二次进入的时候就return出去了
                    if (_isRefreshing == YES) {
                        return;
                    }
                    i--;
                    _Id = [_storiseArr[i] integerValue];
                    // 因为每次加载setDataUp这个方法都会创建一个新的webView所以要删除
                    [_webView removeFromSuperview];
                    [self setDataUp];
                  }
              }
           }
        }
        
        // 设置下提加载下一界面
         CGFloat dY = _SView.contentSize.height - kScreenHeight;
        if (y > dY + 50) {
            NSString *str = [NSString stringWithFormat:@"%ld",_Id];
            NSString *lastStr = _storiseArr.lastObject;
            // 判断如果是最后一个就什么都不做
            if ([str isEqualToString:lastStr]) {
                return;
            }else{
                for (int i = 0; i < _storiseArr.count; i++) {
                    if ([str isEqualToString:_storiseArr[i]]) {
                        i++;
                        _Id = [_storiseArr[i] integerValue];
                        i--;
                        // 因为每次加载setDataUp这个方法都会创建一个新的webView所以要删除
                        [_webView removeFromSuperview];
                        // 如果从第一个webView以上提加载的方式进入第二个界面,此时页面不会删除不会触发dealloc所以此时如果从webView返回上一个控制器  _model.image != nil  这个判断条件就不会生效(只有第一个界面_model.image才不为空,所以跳出才会生效)所以在这里直接删除掉观察者
                        if (_model.image != nil) {
                            [self.SView removeObserver:self forKeyPath:@"contentOffset"];
                        }
                        [self setDataUp];
                    }
                }
                
    
            }
        }
        
        
    }
}

// 把状态移除放在停止移动里面
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _isRefreshing = NO;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
